package com.example.featuresdk.analytics

import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

@Composable
fun ScreenAnalytics(lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
                    onStart: (name: String) -> Unit = { name -> AnalyticsDelegate.instance.trackPage(name) }, // Send the 'started' analytics event
                    screenName:String = "Unknown",
                    screenContent: @Composable ()-> Unit){

    // Safely update the current lambdas when a new one is provided
    val currentOnStart by rememberUpdatedState(onStart)

    // If `lifecycleOwner` changes, dispose and reset the effect
    DisposableEffect(lifecycleOwner) {
        // Create an observer that triggers our remembered callbacks for sending analytics events
        val observer = LifecycleEventObserver { _, event ->
            when(event){
                Lifecycle.Event.ON_START -> currentOnStart(screenName)
                else -> {
                    //Log.i("ScreenLoadAnalytics", "event=${event.name} screenName=$screenName lifecycleOwner=$source")
                }
            }
        }

        // Add the observer to the lifecycle
        lifecycleOwner.lifecycle.addObserver(observer)

        // When the effect leaves the Composition, remove the observer
        onDispose {
            //Log.e("ScreenLoadAnalytics","onDispose: lifecycleOwner=$lifecycleOwner   screenName=$screenName")
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    screenContent()
}